package com.myapp.wicket;

import org.apache.wicket.PageParameters;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.PageParameters;
import org.apache.wicket.extensions.markup.html.repeater.data.table.DefaultDataTable;
import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;
import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.model.Model;
import org.apache.wicket.markup.html.link.Link;


import repository.*;
import dto.*;

import java.util.*;
public final class OrderConfirmationPage extends WebPage implements AuthenticatedWebPage {

    private ProductRepository productRepositoty=new ProductRepository();
    private OrderRepository orderRepositoty=new OrderRepository();
    private OrderItemRepository orderItemRepository=new OrderItemRepository();
    
    public OrderConfirmationPage() {
        super();
    }
    
    public OrderConfirmationPage(PageParameters params) 
    { 
       String  selectedIds = params.getString("ids");
       String [] strIds = selectedIds.split(",");
       List<Integer> ids=new ArrayList<Integer>();
       for (int i=0;i<strIds.length;i++)
       {
           ids.add(Integer.parseInt(strIds[i]));
       }
       List<Product> selectedProducts=new ArrayList<Product>();
       
       double totalPrice=0;
       
       for (int i=0;i<ids.size();i++)
       {
           selectedProducts.add(productRepositoty.getById(ids.get(i)));
           totalPrice+=selectedProducts.get(i).price;
       }
       
         //creating new order
         Calendar cal = Calendar.getInstance();
         final SignInSession session = (SignInSession)getSession();
         orderRepositoty.Create(new Order(0,cal.getTime().toString(),totalPrice,session.getUserId()));
         final int orderId=orderRepositoty.GetIdByStatus(0);
         orderRepositoty.UpdateSatusToCreated();
         for (Product product : selectedProducts)
         {
             orderItemRepository.Create(new OrderItem(0,product.id, orderId));
             product.onStorage--;
             productRepositoty.UpdateProduct(product);
         }
       
        add(new Label("totalPrice", "Total Price: "+totalPrice));
        
        add(new Link("confirmItemsLink")
        {
            @Override
            public void onClick()
            {
              orderRepositoty.UpdateSatusToConfirmed(orderId);
              setResponsePage(Index.class);
            }
        });
        List<IColumn<Product>> columns = new ArrayList<IColumn<Product>>();
        columns.add(new PropertyColumn<Product>(Model.of("Name"), "name", "name"));
	columns.add(new PropertyColumn<Product>(Model.of("Price"), "price","price"));
        
        add(new DefaultDataTable<Product>("selectedProducts", columns, new ProductsProvider(selectedProducts), 10));
 }
}
